package top.yueyazhui.order.service.impl;

import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.yueyazhui.common.feign.AccountFeign;
import top.yueyazhui.order.mapper.OrderMapper;
import top.yueyazhui.order.service.OrderService;

import java.math.BigDecimal;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    AccountFeign accountFeign;
    @Autowired
    OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean prepare(BusinessActionContext businessActionContext, String userId, String commodityCode, Integer count, Double money) {
        // 扣款
        boolean result = accountFeign.prepare(businessActionContext, userId, money);
        log.info("用户：{}，商品：{}，数量：{}，总价：{}；预下单成功", userId, commodityCode, count, money);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean commit(BusinessActionContext businessActionContext) {
        String userId = ((String) businessActionContext.getActionContext("userId"));
        String commodityCode = ((String) businessActionContext.getActionContext("commodityCode"));
        Integer count = ((Integer) businessActionContext.getActionContext("count"));
        Double money = ((BigDecimal) businessActionContext.getActionContext("money")).doubleValue();
        Integer result = orderMapper.addOrder(userId, commodityCode, count, money);
        log.info("用户：{}，商品：{}，数量：{}，总价：{}；下单成功", userId, commodityCode, count, money);
        return result == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rollback(BusinessActionContext businessActionContext) {
        String userId = ((String) businessActionContext.getActionContext("userId"));
        String commodityCode = ((String) businessActionContext.getActionContext("commodityCode"));
        Integer count = ((Integer) businessActionContext.getActionContext("count"));
        Double money = ((BigDecimal) businessActionContext.getActionContext("money")).doubleValue();
        log.info("用户：{}，商品：{}，数量：{}，总价：{}；订单回滚成功", userId, commodityCode, count, money);
        return true;
    }
}
